package com.peng.community.controller;

import com.peng.community.annotation.LoginRequire;
import com.peng.community.constant.CommunityConstant;
import com.peng.community.entity.User;
import com.peng.community.service.UserService;
import com.peng.community.service.impl.FollowService;
import com.peng.community.service.impl.LikeService;
import com.peng.community.util.CommunityUtils;
import com.peng.community.util.HostHolder;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Slf4j
@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {

    @LoginRequire
//    @GetMapping("/setting")
    public String getSettingPage() {
        return "/site/setting";
    }

    @Value("${community.path.domain}")
    private String domain;

    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${server.servlet.context-path}")
    String contextPath;

    @Autowired
    HostHolder hostHolder;

    @Autowired
    UserService userService;

    @Autowired
    FollowService followService;

    @Value("${qiniu.key.access}")
    private String access;

    @Value("${qiniu.key.secret}")
    private String secretKey;

    @Value("${qiniu.bucket.header.name}")
    private String headerBucketName;

    @Value("${quniu.bucket.header.url}")
    private String headerBucketUrl;

    @GetMapping("/setting")
    public String setting(Model model) {
        //1.生成随机文件名
        //文件名即使可以被id唯一确定，也应该避免覆盖行为：1> 存在覆盖前的缓存，在这段时间还是得到老的头像；2> 可以拓展新功能; 3> 存储空间不值钱
        String fileName = CommunityUtils.getUUID();

        //2. 规定响应消息的格式(指的是成功时响应何种消息)
        StringMap stringMap = new StringMap();
        stringMap.put("returnBody",CommunityUtils.toJsonString(0));

        //3. 生成凭证并响应
        Auth auth = Auth.create(access,secretKey);
        String uploadToken = auth.uploadToken(headerBucketName,fileName,3600,stringMap);
        model.addAttribute("uploadToken",uploadToken);
        model.addAttribute("filename",fileName);
        return "/site/setting";
    }

    //存储头像后，用户会更新头像URL
    @PostMapping("/header/url")
    @ResponseBody
    public String updateHeaderUrl(String filename) {
        if (StringUtils.isBlank(filename)) {
            return CommunityUtils.toJsonString(1,"头像文件名不能为空");
        }
        String url = headerBucketUrl + "/" + filename;
        userService.updateHeader(url, hostHolder.getUser().getId());
        return CommunityUtils.toJsonString(0 );
    }

    @LoginRequire
    @Deprecated //废弃
    @PostMapping("/upload")
    public String upload(MultipartFile headImg, Model model) {
        if (headImg == null) {
            model.addAttribute("error", "上传的文件为空");
            return "/site/setting";
        }

        String suffix = headImg.getOriginalFilename().split("\\.")[1];
        log.info("suffix:{}", suffix);

        if (StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "文件名不正确");
            return "/site/setting";
        }

        String filename = CommunityUtils.getUUID() + "." +suffix;
        File file = new File(uploadPath + "/" + filename);

        try {
            headImg.transferTo(file);
        } catch (IOException e) {
            log.error("上传文件异常：{}", e.getMessage());
            throw new RuntimeException(e);
        }

        //更新外链访问路径
        User user = hostHolder.getUser();
        String headerUrl = domain + contextPath + "/user/header/" + filename;
        userService.updateHeader(headerUrl, user.getId());
        return "redirect:/index";
    }

    @LoginRequire
    @Deprecated//废弃
    @GetMapping("/header/{filename}")
    public void getHeadImg(@PathVariable("filename")String filename, HttpServletResponse response) {
        System.out.println("filename:" + filename);
        String sufffix = filename.split("\\.")[1];
        String path = uploadPath + "/" + filename;

        //设置响应类型
        response.setContentType("image/" + sufffix);
        try (
                FileInputStream fis = new FileInputStream(new File(path));
                ServletOutputStream outputStream = response.getOutputStream()
        ) {
            byte[] bytes = new byte[1024];
            int b;
            while ((b = fis.read(bytes)) != -1) {
                outputStream.write(bytes,0,b);
            }
        }  catch (IOException e) {
            log.error("得到头像失败{}", e.getMessage());
            e.printStackTrace();
        }
    }

    @Autowired
    LikeService likeService;

    @GetMapping("/profile/{userId}")
    public String getUserProfile(@PathVariable("userId")int userId, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        model.addAttribute("user",user);

        //点赞数量
        int userLikeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount", userLikeCount);

        //当前页面用户关注其他用户的数量
        long followeeCount = followService.findFolloweeCount(user.getId(), ENTITY_TYPE_USER);
        model.addAttribute("followeeCount", followeeCount);

        //当前页面用户被关注的数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, user.getId());
        model.addAttribute("followerCount", followerCount);

        //当前登录用户是否关注这个页面的用户
        boolean hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(), ENTITY_TYPE_USER, user.getId());
        model.addAttribute("hasFollowed", hasFollowed);

        log.info("被关注:{}, 关注：{}", followerCount, followeeCount);

        return "/site/profile";
    }
}
